import { authClient } from "@/lib/auth-client";
{{#if (eq api "orpc")}}
import { orpc } from "@/utils/orpc";
import { useQuery } from "@tanstack/solid-query";
{{/if}}
import { createFileRoute, redirect } from "@tanstack/solid-router";

export const Route = createFileRoute("/dashboard")({
	component: RouteComponent,
	beforeLoad: async () => {
		const session = await authClient.getSession();
		if (!session.data) {
			redirect({
				to: "/login",
				throw: true,
			});
		}
		{{#if (eq payments "polar")}}
		const { data: customerState } = await authClient.customer.state();
		return { session, customerState };
		{{else}}
		return { session };
		{{/if}}
	},
});

function RouteComponent() {
	const context = Route.useRouteContext();

	const session = context().session;
	{{#if (eq payments "polar")}}
	const customerState = context().customerState;
	{{/if}}

	{{#if (eq api "orpc")}}
	const privateData = useQuery(() => orpc.privateData.queryOptions());
	{{/if}}

	{{#if (eq payments "polar")}}
	const hasProSubscription = () =>
		customerState?.activeSubscriptions?.length! > 0;
	{{/if}}

	return (
		<div>
			<h1>Dashboard</h1>
			<p>Welcome {session.data?.user.name}</p>
			{{#if (eq api "orpc")}}
			<p>API: {privateData.data?.message}</p>
			{{/if}}
			{{#if (eq payments "polar")}}
			<p>Plan: {hasProSubscription() ? "Pro" : "Free"}</p>
			{hasProSubscription() ? (
				<button onClick={async () => await authClient.customer.portal()}>
					Manage Subscription
				</button>
			) : (
				<button
					onClick={async () => await authClient.checkout({ slug: "pro" })}
				>
					Upgrade to Pro
				</button>
			)}
			{{/if}}
		</div>
	);
}
